
import dayjs from 'dayjs';
import { AppointTimeDataItem, AppointApplyStudentSchema } from '../types/appoint';

/**
 * 将数字时间段转换为文本表示
 * @param period 时间段数字（0:全天, 1:上午, 2:下午）
 * @returns 时间段文本
 */
export const studentPeriod = (period: number) => {
  switch(period) {
    case 1:
      return '上午';
    case 2:
      return '下午';
    case 0:
    default:
      return '全天';
  }
};

export const isWorkTime = (curTime: dayjs.Dayjs, workStartTime: dayjs.Dayjs, workEndTime: dayjs.Dayjs) => {
  return (curTime.isAfter(workStartTime) || curTime.isSame(workStartTime)) && (curTime.isBefore(workEndTime) || curTime.isSame(workEndTime));
}

/**
 * 生成从0点到24点的完整时间段数据
 * @param workStartTime 工作开始时间
 * @param workEndTime 工作结束时间
 * @returns 格式化后的时间段数组
 */
export const generateInitialSlots = (workStartTime: dayjs.Dayjs, workEndTime: dayjs.Dayjs, selectedDate: dayjs.Dayjs, coachStatus: number = 0) => {
    const initialSlots:any = [];
    const startOfDay = dayjs(`${selectedDate.format('YYYY-MM-DD')} 00:00`, 'YYYY-MM-DD HH:mm');
    const endOfDay = dayjs(`${selectedDate.format('YYYY-MM-DD')} 24:00`, 'YYYY-MM-DD HH:mm');
    let currentTime = startOfDay.clone();
    // 添加完整日期信息到工作时间
    const workStartTimeWithDate = dayjs(`${selectedDate.format('YYYY-MM-DD')} ${workStartTime.format('HH:mm')}`, 'YYYY-MM-DD HH:mm');
    const workEndTimeWithDate = dayjs(`${selectedDate.format('YYYY-MM-DD')} ${workEndTime.format('HH:mm')}`, 'YYYY-MM-DD HH:mm');

    console.log('当前工作时间:', workStartTimeWithDate.format('HH:mm'), workEndTimeWithDate.format('HH:mm'));

    while (currentTime.isBefore(endOfDay)) {
      const nextHour = currentTime.clone().add(1, 'hour');
      let slotEndTime = nextHour.isAfter(endOfDay) ? endOfDay : nextHour;

      // 检查当前时间段是否与工作开始时间重叠
      if (currentTime.isBefore(workStartTimeWithDate) && nextHour.isAfter(workStartTimeWithDate)) {
        // 拆分时间段: 当前时间 -> 工作开始时间
        const duration1 = workStartTimeWithDate.diff(currentTime, 'hour', true);
        initialSlots.push({
          studentId: 0,
          startTime: currentTime.format('HH:mm'),
          duration: duration1,
          subject: '',
          status: 3, // 未开放
          isMorningSlot: true,
          isEveningSlot: false,
          isWorkingSlot: false,
          display: `${currentTime.format('HH:mm')} - ${workStartTimeWithDate.format('HH:mm')}`,
        });

        // 工作开始时间 -> 下一小时
        const duration2 = nextHour.diff(workStartTimeWithDate, 'hour', true);
        initialSlots.push({
          studentId: 0,
          startTime: workStartTimeWithDate.format('HH:mm'),
          duration: duration2,
          subject: '',
          status: coachStatus, // 可预约
          isMorningSlot: false,
          isEveningSlot: false,
          isWorkingSlot: true,
          display: `${workStartTimeWithDate.format('HH:mm')} - ${nextHour.format('HH:mm')}`,
        });
        currentTime = nextHour;
        continue;
      }

      // 检查当前时间段是否与工作结束时间重叠
      if (currentTime.isBefore(workEndTimeWithDate) && nextHour.isAfter(workEndTimeWithDate)) {
        // 拆分时间段: 当前时间 -> 工作结束时间
        const duration1 = workEndTimeWithDate.diff(currentTime, 'hour', true);
        initialSlots.push({
          studentId: 0,
          startTime: currentTime.format('HH:mm'),
          duration: duration1,
          subject: '',
          status: coachStatus, // 可预约
          isMorningSlot: false,
          isEveningSlot: false,
          isWorkingSlot: true,
          display: `${currentTime.format('HH:mm')} - ${workEndTimeWithDate.format('HH:mm')}`
        });

        // 工作结束时间 -> 下一小时
        const duration2 = nextHour.diff(workEndTimeWithDate, 'hour', true);
        initialSlots.push({
          studentId: 0,
          startTime: workEndTimeWithDate.format('HH:mm'),
          duration: duration2,
          subject: '',
          status: 3, // 未开放
          isMorningSlot: false,
          isEveningSlot: true,
          isWorkingSlot: false,
          display: `${workEndTimeWithDate.format('HH:mm')} - ${nextHour.format('HH:mm')}`
        });
        currentTime = nextHour;
        continue;
      }

      // 常规时间段处理
      const duration = slotEndTime.diff(currentTime, 'hour', true);
      let status = 3; // 默认未开放

      if (isWorkTime(currentTime, workStartTimeWithDate, workEndTimeWithDate)) {
        status = coachStatus; // 可预约
      }

      console.log(992, currentTime.format('HH:mm'), duration, status, isWorkTime(currentTime, workStartTimeWithDate, workEndTimeWithDate))

      initialSlots.push({
        studentId: 0,
        startTime: currentTime.format('HH:mm'),
        duration: duration,
        subject: '',
        status: status,
        isMorningSlot: currentTime.isBefore(workStartTimeWithDate),
        isEveningSlot: currentTime.isAfter(workEndTimeWithDate),
        isWorkingSlot: isWorkTime(currentTime, workStartTimeWithDate, workEndTimeWithDate),
        display: `${currentTime.format('HH:mm')} - ${nextHour.format('HH:mm')}`
      });

      currentTime = nextHour;
    }
    return initialSlots
}

/**
 * 智能排班结果
 */
export interface SmartAssignResult {
  // 是否成功
  success: boolean;
  // 消息
  message: string;
  // 排班后的数据
  newVehiclePages: Array<Array<AppointTimeDataItem>>;
  // 未分配的学员
  unassignedStudents: AppointApplyStudentSchema[];
}

/**
 * 确保时间段连续且不重叠
 * @param currentPageData 当前页面的时间段数据
 * @param startOfDay 一天的开始时间
 * @param endOfDay 一天的结束时间
 * @param workStartTimeWithDate 带日期的工作开始时间
 * @param workEndTimeWithDate 带日期的工作结束时间
 */
export const ensureContinuousTimeSlots = (
  currentPageData: AppointTimeDataItem[],
  startOfDay: dayjs.Dayjs,
  endOfDay: dayjs.Dayjs,
  workStartTimeWithDate: dayjs.Dayjs,
  workEndTimeWithDate: dayjs.Dayjs
): void => {
  if (currentPageData.length === 0) return;

  // 检查工作开始时间是否为整点
  const isWorkStartIntegerHour = workStartTimeWithDate.minute() === 0;
  // 检查工作结束时间是否为整点
  const isWorkEndIntegerHour = workEndTimeWithDate.minute() === 0;

  // 1. 先按开始时间排序所有时间段
  currentPageData.sort((a, b) => {
    const aTime = dayjs(`${startOfDay.format('YYYY-MM-DD')} ${a.startTime}`, 'YYYY-MM-DD HH:mm');
    const bTime = dayjs(`${startOfDay.format('YYYY-MM-DD')} ${b.startTime}`, 'YYYY-MM-DD HH:mm');
    return aTime.isBefore(bTime) ? -1 : 1;
  });

  // 2. 确保从0点开始
  const firstSlot = currentPageData[0];
  const firstSlotStartTime = dayjs(`${startOfDay.format('YYYY-MM-DD')} ${firstSlot.startTime}`, 'YYYY-MM-DD HH:mm');
  if (!firstSlotStartTime.isSame(startOfDay)) {
    currentPageData.unshift({
      studentId: 0,
      startTime: '00:00',
      duration: firstSlotStartTime.diff(startOfDay, 'hour', true),
      subject: '',
      status: 3, // 未开放
      isMorningSlot: true,
      isEveningSlot: false,
      isWorkingSlot: false,
      display: `00:00 - ${firstSlot.startTime}`
    });
  }

  // 3. 处理非整点工作开始时间
  if (!isWorkStartIntegerHour) {
    const workStartHour = workStartTimeWithDate.startOf('hour');
    const workStartSlotIndex = currentPageData.findIndex(slot => {
      const slotStartTime = dayjs(`${startOfDay.format('YYYY-MM-DD')} ${slot.startTime}`, 'YYYY-MM-DD HH:mm');
      return slotStartTime.isSame(workStartHour);
    });

    if (workStartSlotIndex !== -1 && currentPageData[workStartSlotIndex].studentId === 0) {
      // 如果工作开始时间所在的小时段没有被分配，则拆分
      const slot = currentPageData[workStartSlotIndex];
      const slotStartTime = dayjs(`${startOfDay.format('YYYY-MM-DD')} ${slot.startTime}`, 'YYYY-MM-DD HH:mm');

      // 拆分时间段: 开始 -> 工作开始时间
      const duration1 = workStartTimeWithDate.diff(slotStartTime, 'hour', true);
      if (duration1 > 0) {
        const slot1 = {
          ...slot,
          duration: duration1,
          isWorkingSlot: false,
          status: 3,
          display: `${slot.startTime} - ${workStartTimeWithDate.format('HH:mm')}`
        };
        currentPageData.splice(workStartSlotIndex, 1, slot1);
      }

      // 工作开始时间 -> 结束
      const duration2 = slot.duration - duration1;
      if (duration2 > 0) {
        const slot2 = {
          ...slot,
          startTime: workStartTimeWithDate.format('HH:mm'),
          duration: duration2,
          isWorkingSlot: true,
          status: 0,
          display: `${workStartTimeWithDate.format('HH:mm')} - ${slotStartTime.add(slot.duration, 'hour').format('HH:mm')}`
        };
        currentPageData.splice(workStartSlotIndex, 1, slot2);
      }
    }
  }

  // 4. 处理非整点工作结束时间
  if (!isWorkEndIntegerHour) {
    const workEndHour = workEndTimeWithDate.startOf('hour');
    const workEndSlotIndex = currentPageData.findIndex(slot => {
      const slotStartTime = dayjs(`${startOfDay.format('YYYY-MM-DD')} ${slot.startTime}`, 'YYYY-MM-DD HH:mm');
      return slotStartTime.isSame(workEndHour);
    });

    if (workEndSlotIndex !== -1 && currentPageData[workEndSlotIndex].studentId === 0) {
      // 如果工作结束时间所在的小时段没有被分配，则拆分
      const slot = currentPageData[workEndSlotIndex];
      const slotStartTime = dayjs(`${startOfDay.format('YYYY-MM-DD')} ${slot.startTime}`, 'YYYY-MM-DD HH:mm');

      // 拆分时间段: 开始 -> 工作结束时间
      const duration1 = workEndTimeWithDate.diff(slotStartTime, 'hour', true);
      if (duration1 > 0) {
        const slot1 = {
          ...slot,
          duration: duration1,
          isWorkingSlot: true,
          status: 0,
          display: `${slot.startTime} - ${workEndTimeWithDate.format('HH:mm')}`
        };
        currentPageData.splice(workEndSlotIndex, 1, slot1);
      }


      // 工作结束时间 -> 结束
      const duration2 = slot.duration - duration1;
      if (duration2 > 0) {
        const slot2 = {
          ...slot,
          startTime: workEndTimeWithDate.format('HH:mm'),
          duration: duration2,
          isWorkingSlot: false,
          status: 3,
          display: `${workEndTimeWithDate.format('HH:mm')} - ${slotStartTime.add(slot.duration, 'hour').format('HH:mm')}`
        };
        currentPageData.splice(workEndSlotIndex, 1, slot2);
      }
    }
  }

  // 5. 检查并修复中间时间段的连续性和重叠
  for (let i = 1; i < currentPageData.length; i++) {
    const prevSlot = currentPageData[i - 1];
    const currSlot = currentPageData[i];

    const prevSlotEndTime = dayjs(`${startOfDay.format('YYYY-MM-DD')} ${prevSlot.startTime}`, 'YYYY-MM-DD HH:mm').add(prevSlot.duration, 'hour');
    const currSlotStartTime = dayjs(`${startOfDay.format('YYYY-MM-DD')} ${currSlot.startTime}`, 'YYYY-MM-DD HH:mm');
    const currSlotEndTime = currSlotStartTime.add(currSlot.duration, 'hour');

    // 检查是否有时间间隔
    if (!prevSlotEndTime.isSame(currSlotStartTime)) {
      const isWorkingSlot = currSlotStartTime.isAfter(workStartTimeWithDate) && prevSlotEndTime.isBefore(workEndTimeWithDate);

      // 添加缺失的时间段
      currentPageData.splice(i, 0, {
        studentId: 0,
        startTime: prevSlotEndTime.format('HH:mm'),
        duration: currSlotStartTime.diff(prevSlotEndTime, 'hour', true),
        subject: '',
        status: isWorkingSlot ? 0 : 3,
        isWorkingSlot: currSlot.studentId?true:isWorkingSlot,
        isMorningSlot: currSlot.studentId?false:currSlotStartTime.isBefore(workStartTimeWithDate),
        isEveningSlot: currSlot.studentId?false:prevSlotEndTime.isAfter(workEndTimeWithDate),
        display: `${prevSlotEndTime.format('HH:mm')} - ${currSlot.startTime}`
      });
      i++;
    }
    // 检查是否重叠
    else if (prevSlotEndTime.isAfter(currSlotStartTime)) {
      // 完全重叠：当前槽位被前一个槽位完全覆盖
      if (prevSlotEndTime.isAfter(currSlotEndTime)) {
        currentPageData.splice(i, 1);
        i--;
      }
      // 部分重叠：调整当前槽位的开始时间和时长
      else {
        const overlapDuration = prevSlotEndTime.diff(currSlotStartTime, 'hour', true);
        currentPageData[i] = {
          ...currSlot,
          startTime: prevSlotEndTime.format('HH:mm'),
          duration: currSlot.duration - overlapDuration,
          display: `${prevSlotEndTime.format('HH:mm')} - ${currSlotEndTime.format('HH:mm')}`
        };
      }
    }
  }

  // 6. 确保时间段结束于24点
  const lastSlot = currentPageData[currentPageData.length - 1];
  const lastSlotEndTime = dayjs(`${startOfDay.format('YYYY-MM-DD')} ${lastSlot.startTime}`, 'YYYY-MM-DD HH:mm').add(lastSlot.duration, 'hour');

  if (!lastSlotEndTime.isSame(endOfDay)) {
    if (lastSlotEndTime.isBefore(endOfDay)) {
      currentPageData.push({
        studentId: 0,
        startTime: lastSlotEndTime.format('HH:mm'),
        duration: endOfDay.diff(lastSlotEndTime, 'hour', true),
        subject: '',
        status: 3, // 未开放
        isMorningSlot: lastSlotEndTime.isBefore(workStartTimeWithDate),
        isEveningSlot: lastSlotEndTime.isAfter(workEndTimeWithDate),
        isWorkingSlot: isWorkTime(lastSlotEndTime, workStartTimeWithDate, workEndTimeWithDate),
        display: `${lastSlotEndTime.format('HH:mm')} - 24:00`
      });
    } else {
      // 调整超过24点的时间段
      currentPageData[currentPageData.length - 1] = {
        ...lastSlot,
        duration: endOfDay.diff(dayjs(`${startOfDay.format('YYYY-MM-DD')} ${lastSlot.startTime}`, 'YYYY-MM-DD HH:mm'), 'hour', true),
        display: `${lastSlot.startTime} - 24:00`
      };
    }
  }
};


/**
 * 智能排班主函数
 * @param students 待排班的学员列表
 * @param workTime 教练工作时间 [startTime, endTime]
 * @param vehiclePages 当前排班数据
 * @param options 智能排班选项
 * @returns 排班结果
 */
export const smartAssign =(
    currentPage: number,
    students: AppointApplyStudentSchema[],
    workTime: [dayjs.Dayjs, dayjs.Dayjs],
    vehiclePages: Array<Array<AppointTimeDataItem>>,
    selectedDate: dayjs.Dayjs,
    setStudents: (students: AppointApplyStudentSchema[]) => void): SmartAssignResult => {
  try {
    // 深拷贝当前排班数据，避免直接修改原始数据
    const newVehiclePages = JSON.parse(JSON.stringify(vehiclePages));
    const currentPageData = newVehiclePages[currentPage]; // 假设只处理第一页

    // 添加日期信息到工作时间
    const workStartTimeWithDate = dayjs(`${selectedDate.format('YYYY-MM-DD')} ${workTime[0].format('HH:mm')}`, 'YYYY-MM-DD HH:mm');
    const workEndTimeWithDate = dayjs(`${selectedDate.format('YYYY-MM-DD')} ${workTime[1].format('HH:mm')}`, 'YYYY-MM-DD HH:mm');
    const startOfDay = dayjs(`${selectedDate.format('YYYY-MM-DD')} 00:00`, 'YYYY-MM-DD HH:mm');
    const endOfDay = dayjs(`${selectedDate.format('YYYY-MM-DD')} 24:00`, 'YYYY-MM-DD HH:mm');
    const noonTime = dayjs(`${selectedDate.format('YYYY-MM-DD')} 12:00`, 'YYYY-MM-DD HH:mm');

    // 筛选出未被分配的学生
    const assignedStudents = currentPageData.filter((slot: AppointTimeDataItem) => {return slot.studentId !== 0});
    console.log('已分配的学员：', assignedStudents);
    
    let allStudents = students.filter((s: AppointApplyStudentSchema) => {
      return s.user_id && s.status == 1 && !s.assigned && !assignedStudents.some((assigned: AppointTimeDataItem) => assigned.studentId === s.user_id);

    });
    console.log('未分配的学员：', allStudents)

    // 按period分组
    const morningStudents = allStudents.filter(s => s.period === 1).sort((a, b) => b.durtime - a.durtime);
    const afternoonStudents = allStudents.filter(s => s.period === 2).sort((a, b) => b.durtime - a.durtime);
    const fulltimeStudents = allStudents.filter(s => s.period === 0).sort((a, b) => b.durtime - a.durtime);
    console.log('上午学员：', morningStudents);
    console.log('下午学员：', afternoonStudents);
    console.log('全时间学员：', fulltimeStudents)

    // 记录未分配的学员
    let unassignedStudents: AppointApplyStudentSchema[] = [];
    
    // 定义时间段检查函数
    const isInMorning = (time: dayjs.Dayjs) => time.isBefore(noonTime);
    const isInAfternoon = (time: dayjs.Dayjs) => time.isAfter(noonTime) || time.isSame(noonTime);
    
    // 分配函数
    const assignStudents = (students: AppointApplyStudentSchema[], isSuitableTime: (time: dayjs.Dayjs) => boolean) => {
      students.forEach(student => {
        const duration = student.durtime; // 学员预约时长
        let assigned = false;

        // 查找可用时间段
        for (let i = 0; i < currentPageData.length; i++) {
          const slot = currentPageData[i];
          if (slot.studentId === 0 && slot.isWorkingSlot && slot.status === 0) {
            const slotStartTime = dayjs(`${selectedDate.format('YYYY-MM-DD')} ${slot.startTime}`, 'YYYY-MM-DD HH:mm');
            const slotEndTime = slotStartTime.add(slot.duration, 'hour');

            // 检查时间段是否合适
            if (isSuitableTime(slotStartTime) && isSuitableTime(slotEndTime.add(-1, 'second'))) {
              // 检查是否有足够的连续时间段
              let consecutiveDuration = 0;
              let startIndex = i;
              let endIndex = i;
              while (endIndex < currentPageData.length && currentPageData[endIndex].studentId === 0 && currentPageData[endIndex].isWorkingSlot && currentPageData[endIndex].status === 0) {
                consecutiveDuration += currentPageData[endIndex].duration;
                if (consecutiveDuration >= duration) break;
                endIndex++;
              }

              if (consecutiveDuration >= duration) {
                // 分配时间段
                const firstSlot = currentPageData[startIndex];
                const firstSlotStartTime = dayjs(`${selectedDate.format('YYYY-MM-DD')} ${firstSlot.startTime}`, 'YYYY-MM-DD HH:mm');
                const actualEndTime = firstSlotStartTime.add(duration, 'hour');

                // 确保在工作时间内
                if (actualEndTime.isBefore(workEndTimeWithDate) || actualEndTime.isSame(workEndTimeWithDate)) {
                  // 更新第一个槽位
                  currentPageData[startIndex] = {
                    ...firstSlot,
                    studentId: student.user_id,
                    status: 1, // 已预约
                    duration: duration,
                    subject: student.subject,
                    display: `${firstSlot.startTime} - ${actualEndTime.format('HH:mm')}`
                  };
                  students.forEach((s: AppointApplyStudentSchema) => {
                    if(s.user_id === student.user_id) {
                      s.assigned = true;
                    }
                  })

                  // 处理剩余时间段
                  if (consecutiveDuration > duration) {
                    const remainingDuration = consecutiveDuration - duration;
                    const newSlotStartTime = actualEndTime.format('HH:mm');
                    const newSlotEndTime = actualEndTime.add(remainingDuration, 'hour');
                    const newSlotEndTimeWithDate = dayjs(`${selectedDate.format('YYYY-MM-DD')} ${newSlotEndTime.format('HH:mm')}`, 'YYYY-MM-DD HH:mm');
                    const finalEndTime = newSlotEndTimeWithDate.isAfter(workEndTimeWithDate) ? workEndTimeWithDate : newSlotEndTimeWithDate;
                    const finalDuration = finalEndTime.diff(actualEndTime, 'hour', true);

                    const newSlot: AppointTimeDataItem = {
                      studentId: 0,
                      startTime: newSlotStartTime,
                      duration: finalDuration,
                      subject: '',
                      status: 0, // 可预约
                      isWorkingSlot: finalEndTime.isBefore(workEndTimeWithDate) || finalEndTime.isSame(workEndTimeWithDate),
                      isMorningSlot: finalEndTime.isBefore(workStartTimeWithDate),
                      isEveningSlot: finalEndTime.isAfter(workEndTimeWithDate),
                      display: `${newSlotStartTime} - ${finalEndTime.format('HH:mm')}`
                    };
                    currentPageData.splice(endIndex + 1, 0, newSlot);
                  }

                  // 删除中间已被合并的槽位
                  if (endIndex > startIndex) {
                    currentPageData.splice(startIndex + 1, endIndex - startIndex);
                  }
                  assigned = true;
                  break;
                }
              }
            }
          }
        }

        if (!assigned) {
          unassignedStudents.push({...student});
          students.forEach((s: AppointApplyStudentSchema) => {
            if(s.user_id === student.user_id) {
              s.assigned = false;
            }
          })
        }
      });
    };

    // 先分配上午和下午的学员
    assignStudents(morningStudents, isInMorning);
    assignStudents(afternoonStudents, isInAfternoon);

    // 分配全天学员
    assignStudents(fulltimeStudents, () => true);

    // 尝试调整全天学员以容纳未分配的学员
    const stillUnassigned = [...unassignedStudents];
    unassignedStudents = [];

    if (stillUnassigned.length > 0) {
      console.log('尝试调整全天学员以容纳未分配的学员');
      // 找出已分配的全天学员
      const assignedFulltimeStudents = currentPageData
        .filter((slot: AppointTimeDataItem) => slot && slot.studentId !== undefined && slot.studentId > 0) // 添加slot不为空和studentId不为undefined的检查
        .map((slot: AppointTimeDataItem) => {
          const student = allStudents.find(s => s && s.user_id === slot.studentId); // 添加s不为空的检查
          return student && student.period === 0 ? {slot, student} : null;
        })
        .filter((item: any) => item !== null) as Array<{slot: AppointTimeDataItem, student: AppointApplyStudentSchema}>; // 使用更严格的过滤

      // 尝试为未分配学员寻找空间
      stillUnassigned.forEach(student => {
        let assigned = false;
        // 检查是否可以调整全天学员
        for (const item of assignedFulltimeStudents) {
          if (!item || !item.slot || !item.student) continue; // 添加空检查
          const {slot, student: ftStudent} = item;
          
          // 确保slot有startTime属性
          if (!slot.startTime) continue;

          const slotStartTime = dayjs(`${selectedDate.format('YYYY-MM-DD')} ${slot.startTime}`, 'YYYY-MM-DD HH:mm');
          const slotEndTime = slotStartTime.add(slot.duration, 'hour');

          // 检查当前学员的时间段偏好
          const isMorningStudent = student.period === 1;
          const isAfternoonStudent = student.period === 2;

          // 尝试将全天学员移动到其他时间段
          if (isMorningStudent && isInAfternoon(slotStartTime)) {
            // 上午学员需要上午时间，尝试将全天学员移到下午
            const newStartTime = noonTime;
            if (newStartTime.add(ftStudent.durtime, 'hour').isBefore(workEndTimeWithDate) || newStartTime.add(ftStudent.durtime, 'hour').isSame(workEndTimeWithDate)) {
              // 检查下午是否有空间
              let hasSpace = true;
              for (let i = 0; i < currentPageData.length; i++) {
                const s = currentPageData[i];
                if (s && s.studentId === 0 && s.isWorkingSlot && s.status === 0) { // 添加s不为空的检查
                  const sStartTime = dayjs(`${selectedDate.format('YYYY-MM-DD')} ${s.startTime}`, 'YYYY-MM-DD HH:mm');
                  if (sStartTime.isSame(newStartTime) || (sStartTime.isBefore(newStartTime) && sStartTime.add(s.duration, 'hour').isAfter(newStartTime))) {
                    // 有重叠，无法移动
                    hasSpace = false;
                    break;
                  }
                }
              }

              if (hasSpace) {
                // 移动全天学员
                const slotIndex = currentPageData.findIndex((s: AppointTimeDataItem) => s && s.studentId === slot.studentId); // 添加s不为空的检查
                if (slotIndex !== -1) {
                  currentPageData[slotIndex] = {
                    ...slot,
                    startTime: newStartTime.format('HH:mm'),
                    display: `${newStartTime.format('HH:mm')} - ${newStartTime.add(ftStudent.durtime, 'hour').format('HH:mm')}`
                  };

                  // 为当前学员分配原来的时间段
                  currentPageData.push({
                    studentId: student.user_id,
                    startTime: slot.startTime,
                    duration: student.durtime,
                    subject: student.subject,
                    status: 1,
                    isWorkingSlot: true,
                    isMorningSlot: true,
                    isEveningSlot: false,
                    display: `${slot.startTime} - ${slotStartTime.add(student.durtime, 'hour').format('HH:mm')}`
                  });

                  student.assigned = true;
                  assigned = true;
                  break;
                }
              }
            }
          } else if (isAfternoonStudent && isInMorning(slotEndTime)) {
            // 下午学员需要下午时间，尝试将全天学员移到上午
            const newEndTime = noonTime;
            if (newEndTime.subtract(ftStudent.durtime, 'hour').isAfter(workStartTimeWithDate) || newEndTime.subtract(ftStudent.durtime, 'hour').isSame(workStartTimeWithDate)) {
              const newStartTime = newEndTime.subtract(ftStudent.durtime, 'hour');
              // 检查上午是否有空间
              let hasSpace = true;
              for (let i = 0; i < currentPageData.length; i++) {
                const s = currentPageData[i];
                if (s && s.studentId === 0 && s.isWorkingSlot && s.status === 0) { // 添加s不为空的检查
                  const sEndTime = dayjs(`${selectedDate.format('YYYY-MM-DD')} ${s.startTime}`, 'YYYY-MM-DD HH:mm').add(s.duration, 'hour');
                  if (sEndTime.isSame(newEndTime) || (s.startTime.isAfter(newStartTime) && s.startTime.isBefore(newEndTime))) {
                    // 有重叠，无法移动
                    hasSpace = false;
                    break;
                  }
                }
              }

              if (hasSpace) {
                // 移动全天学员
                const slotIndex = currentPageData.findIndex((s: AppointTimeDataItem) => s && s.studentId === slot.studentId); // 添加s不为空的检查
                if (slotIndex !== -1) {
                  currentPageData[slotIndex] = {
                    ...slot,
                    startTime: newStartTime.format('HH:mm'),
                    duration: ftStudent.durtime,
                    display: `${newStartTime.format('HH:mm')} - ${newEndTime.format('HH:mm')}`
                  };

                  // 为当前学员分配原来的时间段
                  currentPageData.push({
                    studentId: student.user_id,
                    startTime: newEndTime.format('HH:mm'),
                    duration: student.durtime,
                    subject: student.subject,
                    status: 1,
                    isWorkingSlot: true,
                    isMorningSlot: false,
                    isEveningSlot: false,
                    display: `${newEndTime.format('HH:mm')} - ${newEndTime.add(student.durtime, 'hour').format('HH:mm')}`
                  });

                  student.assigned = true;
                  assigned = true;
                  break;
                }
              }
            }
          }
        }

        if (!assigned) {
          unassignedStudents.push(student);
        }
      });
    }

    // 确保时间段连续
    ensureContinuousTimeSlots(currentPageData, startOfDay, endOfDay, workStartTimeWithDate, workEndTimeWithDate);

    // 更新学生状态
    allStudents.forEach(s => {
      const found = students.find(student => student.user_id === s.user_id);
      if (found) {
        found.assigned = s.assigned;
      }
    });

    // 标记未分配的学员
    const result = {
      success: true,
      message: unassignedStudents.length > 0 ? `智能排班完成，但有${unassignedStudents.length}名学员未分配` : '智能排班成功',
      newVehiclePages,
      unassignedStudents
    };
    setStudents(students);
    return result;
  } catch (error) {
    return {
      success: false,
      message: `智能排班失败: ${error instanceof Error ? error.message : String(error)}`,
      newVehiclePages: vehiclePages,
      unassignedStudents: []
    };
  }
};
